import requests
import  json
import re
import hashlib  
import shutil 
import os
class   pubVer():
    def  __init__(self):
        pass

    def  readAllDataAndMd5(self,path):
        map=False
        map_md5=False
        software=False
        software_md5=False
        bin=False
        bin_md5=False
        version = False
        def readDataAndMd5(file):
            try:
                fd = open(file,"rb")
                data = fd.read()
                fd.close()
                m = hashlib.md5()
                m.update(data)
                data_md5 = m.hexdigest()
                return data,data_md5
            except Exception as  e:
                return False,False
        
        try:
            lists = os.listdir(path)
            for i in lists:
                if i.find("MAP.zip") != -1:
                    map,map_md5 =  readDataAndMd5(path+"\\"+i)
                    lists.remove(i)
                elif i.find(".zip") != -1 and  i.find("_MAP") == -1:
                    software,software_md5 =  readDataAndMd5(path+"\\"+i)
                    lists.remove(i)
                elif  i.find("_MAP") == -1 and i.find("zip") == -1:
                    softwareLists = os.listdir(path+"\\"+i)
                    version = i
                    for j in  softwareLists:
                        if j.find(".dfota.bin") != -1:
                            bin,bin_md5 =  readDataAndMd5(path+"\\"+i+"\\"+j)
                        pass
                
            return version,map,map_md5,software,software_md5,bin,bin_md5
        except Exception as  e:
                return False,False,False,False,False,False,False
        
        
    

    def publish(self,path,token_id,res):
        post = {
                "token_id":token_id,
                "result":res,
                "msg":"",
                "version":"",
                "software_md5":"",
                "bin_md5":"",
                "map_md5":"",
                }
        files = {
                    "software": ( "", ""),
                    "bin": ( "", ""),
                    "map":( "", "")
                }
        url = "http://erp.openluat.com/api/event/custom_firmware_result"
        if  res == 0:
            print("start publish:"+path)
            version,map,map_md5,software,software_md5,bin,bin_md5 = self.readAllDataAndMd5(path)
            if version :
                post['version'] = version
                post['bin_md5'] = bin_md5
                post['map_md5'] = map_md5
                post['software_md5'] = software_md5

                files["software"] = (version+".zip", software)
                files["bin"] = (version+".dfota.bin", bin)
                files["map"] = (version+"_MAP.zip", map)

                
        res = requests.post(url, data=post,files = files)
        if res.status_code == 200:
            print("publish over")
            return True
        print("publish fail %d"%res.status_code)
        return False
            
    